//app.js
var api = require('/untils/util.js');
App({
  onLaunch: function () {

    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        traceUser: true,
      })
    }
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  wx.clearStorageSync();
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }

    this.globalData = {}
  },
  get_user_info: function (res0, complete) {
    var app = getApp();
    var that = this;
    var rDetail = res0.detail;
    //拒绝授权
    if (rDetail.errMsg == "getUserInfo:fail auth deny") {
      console.log("用户拒绝授权");
      return;
    }
    //将用户存全局变量
    app.globalData.userInfo = rDetail.userInfo;
    app.globalData.encryptedData = rDetail.encryptedData;
    app.globalData.iv = rDetail.iv;
    wx.setStorageSync("userInfo", rDetail.userInfo);
    // console.log(rDetail.userInfo);
    //登录获取code
    wx.login({
      success: function (rt) {
        app.Get(api.wxapp.LoginByCode, {
          code: rt.code,
        },function (res) {
          console.log(res);
          if (res.Code == 200) {
            app.globalData.openId = res.Data.OpenId;
            wx.setStorageSync('UserOpenId', res.Data.OpenId);
            //获取
            app.Get(api.wxapp.GetIsRegiste, {
              OpenId: res.Data.OpenId,
              // WXName: rDetail.userInfo.nickName,
              // WXImg: rDetail.userInfo.avatarUrl,
              // sex: rDetail.userInfo.gender,
              // iv: app.globalData.iv
            }, function (res1) {
              if (res1.Code == 200) {
                that.globalData.token = res1.Data.Token;
                wx.setStorageSync('userToken', res1.Data.Token);
                complete()
              } else {
                // app.WxAlert(res.msg);

                wx.reLaunch({
                  url: '/pages/denglu/denglu'
                })
              }
            });
          } else {
            app.WxAlert(res.msg);
          }
        });
      }
    });
  },
  //封装请求
  WxRequest: function (url, method, param, success, fail, complete) {
    var that = this;
    if (param) {
      param.token = wx.getStorageSync('userToken');
    }
    wx.request({
      url: url,
      data: param,
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: method,
      success: function (res) {
        if (typeof success == "function") {
          if (res.data.Code != 450) {
            success(res.data);
          } else {
            wx.clearStorageSync('userToken');
            wx.redirectTo({
              url: '/pages/authorize/authorize',
            })
          }
        }
      },
      fail: function () {
        if (typeof fail == "function") {
          fail();
        }
      },
      complete: function () {
        if (typeof complete == "function") {
          complete();
        }
      }
    });
  },
  //POST
  Post: function (url, param, success, fail, complete) {
    var that = this;
    that.WxRequest(url, "POST", param, success, fail, complete);
  },
  //GET
  Get: function (url, param, success, fail, complete) {
    var that = this;
    that.WxRequest(url, "GET", param, success, fail, complete);
  },
  //系统公共提示
  WxAlert: function (content) {
    wx.showModal({
      title: '系统提示',
      content: content,
      success: function (res) {
        if (res.confirm) {
          //console.log('用户点击确定')
        } else {
          //console.log('用户点击取消')
        }
      }
    });
  },
  //成功提示
  ShowMsg: function (msg, complete) {
    wx.showToast({
      title: msg,
      icon: 'success',
      duration: 2000,
      complete: complete
    });
  },
  //多张图片上传
  uploadimg: function (data) {
    var that = this,
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    var imgs = data.imgs ? data.imgs : [];
    wx.uploadFile({
      url: api.wxapp.UploadFiles,
      filePath: data.path[i],
      name: 'file', //这里根据自己的实际情况改
      formData: null, //这里是上传图片时一起上传的数据
      success: (resp) => {
        success++; //图片上传成功，图片上传成功的变量+1
        console.log(resp)
        console.log(i);
        var json = JSON.parse(resp.data);
        imgs.push(json.data.FileWebPath[0]);
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
        data.imgs = imgs;
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
          console.log(imgs);
          data.com(data);
        } else { //若图片还没有传完，则继续调用函数
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        console.log(i);

      }
    });
  },
  convertHtmlToText: function convertHtmlToText(inputText) {
    var returnText = "" + inputText;
    returnText = returnText.replace(/<\/div>/ig, '\r\n');
    returnText = returnText.replace(/<\/li>/ig, '\r\n');
    returnText = returnText.replace(/<li>/ig, '  *  ');
    returnText = returnText.replace(/<\/ul>/ig, '\r\n');
    //-- remove BR tags and replace them with line break
    returnText = returnText.replace(/<br\s*[\/]?>/gi, "\r\n");

    //-- remove P and A tags but preserve what's inside of them
    returnText = returnText.replace(/<p.*?>/gi, "\r\n");
    returnText = returnText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");

    //-- remove all inside SCRIPT and STYLE tags
    returnText = returnText.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
    returnText = returnText.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");
    //-- remove all else
    returnText = returnText.replace(/<(?:.|\s)*?>/g, "");

    //-- get rid of more than 2 multiple line breaks:
    returnText = returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\r\n\r\n");

    //-- get rid of more than 2 spaces:
    returnText = returnText.replace(/ +(?= )/g, '');

    //-- get rid of html-encoded characters:
    returnText = returnText.replace(/ /gi, " ");
    returnText = returnText.replace(/&/gi, "&");
    returnText = returnText.replace(/"/gi, '"');
    returnText = returnText.replace(/</gi, '<');
    returnText = returnText.replace(/>/gi, '>');

    return returnText;

  },
})
